package com.tb.interceptor;

import com.tb.util.MyUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 是否有cookie
        Cookie cookie = MyUtils.getCookie(request, "id");
        if (cookie == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        } else if (request.getRequestURI().contains("/backdoor/")) {
            //如果访问后台
            Cookie role = MyUtils.getCookie(request, "role");
            if (role == null) {
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            } else {
                int roleId = Integer.parseInt(role.getValue());
                if (roleId > 1) {
                    //权限不足
                    response.sendRedirect(request.getContextPath() + "/index");
                    return false;
                } else {
                    return true;
                }
            }
        } else {
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }


}
